package com.hunantv.mglive.ui.live;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.LiveDataModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.StarVideoModel;
import com.hunantv.mglive.data.VODModel;
import com.hunantv.mglive.data.VideoModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.ui.entertainer.StarTagActivity;
import com.hunantv.mglive.utils.DanMuUtil;
import com.hunantv.mglive.utils.FastBlur;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.NetworkUtils;
import com.hunantv.mglive.utils.PlayMessageUploadMannager;
import com.hunantv.mglive.utils.ReportUtil;
import com.hunantv.mglive.utils.RoleUtil;
import com.hunantv.mglive.utils.ShareUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.LiveMsgView;
import com.hunantv.mglive.widget.LoadingView;
import com.hunantv.mglive.widget.NotifyDialog;
import com.hunantv.mglive.widget.PersonValueAnim;
import com.hunantv.mglive.widget.loadingView.LoadingViewHelper;
import com.hunantv.mglive.widget.media.IjkVideoView;
import com.hunantv.mglive.widget.media.VideoController;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.parser.android.BiliDanmukuParser;
import master.flame.danmaku.ui.widget.DanmakuView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;


public class StarDetailInfoFragment extends BaseFragment implements GestureDetector.OnGestureListener, View.OnClickListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnErrorListener, IMediaPlayer.OnPreparedListener, NotifyDialog.onButtonClickListener, VideoController.onCountdown, Animation.AnimationListener , IMediaPlayer.OnInfoListener {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final int VIDEO_PAGE_SIZE = 20;
    private static final int CHANGE_KEY_ON_LINE = 1;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final int MSG_TYPE_CHECK_DISPLAY = 1;


    private int mWidth;
    private int mPage = 0;
    private int mCountTime;
    private int mProgress;
    private int mCurPosition = -1;
    private String mCurrVideo;
    private boolean mHasNotify;
    private boolean mShowLoading;
    private boolean mLoadOver;
    //onPause时的视频播放状态
    private boolean mIsPlaying;
    //动态、人气、守护全屏前的视频播放状态
    private boolean mIsFullPlaying;
    private boolean mIsLandView;
    private boolean mAutoRotateOn;
    private Boolean mIsAnim = false;
    private String mCurrVideoPath;
    private String mCurrId;

    private String mParam1;
    private String mParam2;
    //艺人空间页页面切换小图标
//    private ImageView mIvTagIcon;
    private LinearLayout dotLayout;
    private List<View> dotViewList = new ArrayList<>();
    private int oldPosition = 0;//记录上一次点的位置
    private static final int DOT_RIGHT = 1;
    private static final int DOT_LEFT = 2;


    private View mView;
    private View mViewTitle;
    //艺人空间顶部按钮
    private LinearLayout mLlBack;
    private LinearLayout mLlShare;
    private ViewFlipper mViewFlipper;
    private ImageView mBlurBk;

    private StarModel mStarModel;
    private GestureDetector mDetector;
    private FirstViewHolder mFirstVIewHolder;
    private SecondViewHolder mSecondViewHolder;
    private ThridViewHolder mThridViewHolder;
    private onStarDetailVideoCallBack mCallback;
    private List<View> mPageViews = new ArrayList<>();
    private List<StarVideoModel> mVideoList = new ArrayList<>();
    private LoadingView mLoadingView;
    //    private VideoErrorView mVideoErrorView;
    private LoadingViewHelper mLoadingViewHelper;
    private TranslateAnimation mAnimationUpToDown;
    private TranslateAnimation mAnimationUpToDownBack;
    private TranslateAnimation mAnimationDownToUp;
    private TranslateAnimation mAnimationDownToUpBack;


    private ShareUtil mShareUtil;
    private DanMuUtil mDanMuUtil;
    private LiveMsgView mLiveMsgView;
    private VideoController mController;
    private PersonValueAnim mPersonValueAnim;

    private boolean mIsFollow = false;

    private Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case MSG_TYPE_CHECK_DISPLAY:
                    if (mFirstVIewHolder.llTitle.getVisibility() == View.VISIBLE) {
                        mCountTime++;
                        if (mCountTime >= 5) {
                            displayVideoController();
                        } else {
                            mHandler.sendEmptyMessageDelayed(MSG_TYPE_CHECK_DISPLAY, 1000);
                        }
                    }
                    break;
                default:
            }
        }
    };


    public void hasMsg(ChatData chatData) {
        if (mLiveMsgView != null && chatData.getType() == ChatData.CHAT_TYPE_GIFT) {
            mLiveMsgView.displayView(chatData);
        }else if (chatData.getType() == ChatData.CHAT_TYPE_DANMO || chatData.getType() == ChatData.CHAT_TYPE_CONTENT) {
            if (mIsLandView) {
                if (mDanMuUtil != null && !StringUtil.isNullorEmpty(chatData.getBarrageContent())) {
                    mDanMuUtil.addDanmu(chatData.getBarrageContent());
                }
            }
        }
    }

    public void pauseVideo() {
        if (mFirstVIewHolder.mVideoView != null) {
            mIsPlaying = mFirstVIewHolder.mVideoView.isPlaying();
            if (mIsPlaying) {
                mProgress = mFirstVIewHolder.mVideoView.getCurrentPosition();
                mFirstVIewHolder.mVideoView.pause();
            }
            mFirstVIewHolder.iBtnController.setSelected(!mIsPlaying);
        }
    }

    public void resumVideo() {
        if (mFirstVIewHolder.mVideoView != null && !StringUtil.isNullorEmpty(mCurrVideoPath)) {
            setVideoPath();
            if (mProgress > 0) {
                mFirstVIewHolder.mVideoView.seekTo(mProgress);
            }
            if (mIsPlaying) {
                mFirstVIewHolder.mVideoView.start();
            }
        }
    }

    public static StarDetailInfoFragment newInstance(String param1, String param2) {
        StarDetailInfoFragment fragment = new StarDetailInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public StarDetailInfoFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mShareUtil = new ShareUtil(getActivity());
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_star_detail_info_fragment, container, false);
        initStarSpaceView(mView);
        setDanmuView();
        mPersonValueAnim = new PersonValueAnim(getContext(), (ViewGroup) mView);
        return mView;
    }


    void initStarSpaceView(View view) {
        mDetector = new GestureDetector(this.getActivity(), this);
//        ((StarDetailActivity) getActivity()).registerTouchListener(this);

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        initPagerView(view);
        //艺人空间顶部退出按钮
        mLlBack = (LinearLayout) view.findViewById(R.id.ll_star_detail_title_back);
        mLlBack.setOnClickListener(this);

        //艺人空间顶部分享按钮
        mLlShare = (LinearLayout) view.findViewById(R.id.ll_star_detail_title_share);
        mLlShare.setOnClickListener(this);

//        mVideoErrorView = new VideoErrorView(getActivity(), mWidth, (int) (mWidth * 0.75f));
//        mVideoErrorView.setonRefreshListener(this);
        mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewflipper_star_detail_info);
        mViewFlipper.setVisibility(View.INVISIBLE);
        mViewFlipper.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mDetector.onTouchEvent(event);
            }
        });
        dotLayout = (LinearLayout) view.findViewById(R.id.ll_star_detail_page_tag);
        mViewTitle = view.findViewById(R.id.rl_star_detail_title);
        mBlurBk = (ImageView) view.findViewById(R.id.iv_blur_bk);
        initAnim();
    }

    private void initPagerView(View view) {
        mPageViews.clear();
        mSecondViewHolder = new SecondViewHolder();
        mSecondViewHolder.ivICon = (ImageView) view.findViewById(R.id.iv_star_detail_info_icon);
        mSecondViewHolder.ivTag = (ImageView) view.findViewById(R.id.iv_star_detail_info_tag);
        mSecondViewHolder.tvName = (TextView) view.findViewById(R.id.tv_star_detail_star_name);
        mSecondViewHolder.tvDes = (TextView) view.findViewById(R.id.tv_star_detail_star_des);
        mSecondViewHolder.btnAttention = (LinearLayout) view.findViewById(R.id.btn_star_detail_attention);
        mSecondViewHolder.tvAttention = (TextView) view.findViewById(R.id.tv_star_detail_attention);
        mSecondViewHolder.ivAttention = (ImageView) view.findViewById(R.id.iv_star_detail_attention);

        mSecondViewHolder.tagViewGroup = (LinearLayout) view.findViewById(R.id.tagViewGroup);
        mThridViewHolder = new ThridViewHolder();
        mThridViewHolder.tvConstellation = (TextView) view.findViewById(R.id.tv_star_detail_constellation);
        mThridViewHolder.tvGender = (TextView) view.findViewById(R.id.tv_star_detail_gender);
        mThridViewHolder.tvLocation = (TextView) view.findViewById(R.id.tv_star_detail_location);
        mThridViewHolder.tvIntroduce = (TextView) view.findViewById(R.id.tv_star_detail_introduce);

        mFirstVIewHolder = new FirstViewHolder();
        mFirstVIewHolder.mRootView = view.findViewById(R.id.rl_first_view);
        mFirstVIewHolder.iBtnController = (ImageButton) view.findViewById(R.id.ibtn_star_info_video_controller);
        mFirstVIewHolder.iBtnNext = (ImageButton) view.findViewById(R.id.ibtn_star_info_video_next);
        mFirstVIewHolder.mVideoView = (IjkVideoView) view.findViewById(R.id.videoview_star_detail_info);
        mFirstVIewHolder.progressBar = (ProgressBar) view.findViewById(R.id.progressbar_star_detail_bottom);
        mFirstVIewHolder.mVideoView.setViewParams(mWidth, (int) (mWidth * 0.75f));
        mController = new VideoController(getContext());
        mController.setCountdown(this);
        mController.initControllerView(null, mFirstVIewHolder.progressBar, null, null);
        mFirstVIewHolder.mVideoView.setController(mController);
        mController.show();
        mFirstVIewHolder.tvNextInfo = (TextView) view.findViewById(R.id.tv_star_detail_info_next_info);
        mFirstVIewHolder.ivHint = (ImageView) view.findViewById(R.id.iv_star_detail_video_hint);
        mFirstVIewHolder.llTitle = (LinearLayout) view.findViewById(R.id.rl_star_detail_title_video);
        mFirstVIewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_star_detail_video_title);
        mFirstVIewHolder.ibtnBack = (LinearLayout) view.findViewById(R.id.ibtn_star_detail_video_title_back);
        mFirstVIewHolder.ibtn1 = (ImageButton) view.findViewById(R.id.ibtn_star_detail_video_title_1);
        mFirstVIewHolder.ibtn2 = (ImageButton) view.findViewById(R.id.ibtn_star_detail_video_title_2);
        mFirstVIewHolder.mFlMsg = (FrameLayout) view.findViewById(R.id.fl_star_detail_msg);
        mFirstVIewHolder.mDanmakuView = (DanmakuView) view.findViewById(R.id.sv_danmaku);
        mFirstVIewHolder.llStarInfo = (LinearLayout) view.findViewById(R.id.ll_star_detail_bottom_info);
        mFirstVIewHolder.ivIcon = (ImageView) view.findViewById(R.id.iv_star_detail_bottom_star_icon);
        mFirstVIewHolder.tvName = (TextView) view.findViewById(R.id.tv_star_detail_star_info_name);
        mFirstVIewHolder.btnGift = (ImageButton) view.findViewById(R.id.ibtn_star_detail_gif);
        mFirstVIewHolder.mVideoErrorView = view.findViewById(R.id.v_video_error);
        updateViewInfo(mStarModel);
        mLoadingView = new LoadingView(getActivity(), (ViewGroup) mFirstVIewHolder.mRootView);
        mLoadingViewHelper = new LoadingViewHelper(mFirstVIewHolder.mVideoErrorView);
    }

    private void initAnim() {
        mAnimationUpToDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        mAnimationUpToDown.setDuration(300);
        mAnimationUpToDown.setAnimationListener(this);

        mAnimationUpToDownBack = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        mAnimationUpToDownBack.setDuration(300);
        mAnimationUpToDownBack.setAnimationListener(this);

        mAnimationDownToUp = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
        mAnimationDownToUp.setDuration(300);
        mAnimationDownToUp.setAnimationListener(this);

        mAnimationDownToUpBack = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
        mAnimationDownToUpBack.setDuration(300);
        mAnimationDownToUpBack.setAnimationListener(this);
    }

    private void initDots(int size) {
        if (dotLayout != null) {
            dotLayout.removeAllViews();
            dotViewList.clear();
            for (int i = 0; i < size; i++) {
                View view = new View(getContext());
                int margin = (int) getContext().getResources().getDimension(R.dimen.margin_4dp);
                int weight = (int) getContext().getResources().getDimension(R.dimen.margin_6_5dp);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(weight, weight);
                params.setMargins(margin, 0, margin, 0);
                view.setLayoutParams(params);
                if (i == 0) {
                    view.setAlpha(0.8f);
                } else {
                    view.setAlpha(0.4f);
                }

                view.setBackgroundResource(R.drawable.star_info_dot_focused);
                dotViewList.add(view);
                dotLayout.addView(view);
            }
        }
    }

    private void changeDot(int type) {
        int size = dotViewList.size();
        int index = oldPosition;
        if (DOT_LEFT == type) {
            index = index - 1;
        } else if (DOT_RIGHT == type) {
            index = index + 1;
        }
        if (index >= 0 && index < size) {
            View oldDotView = dotViewList.get(oldPosition);
            View nowDotView = dotViewList.get(index);
            oldDotView.setAlpha(0.4f);
            nowDotView.setAlpha(0.8f);
            oldPosition = index;
        }
    }


    private void changeLayouParams() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        if (mIsLandView) {
            RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) mFirstVIewHolder.mVideoView.getLayoutParams();
            //按比例缩放直播窗体
            ps.height = dm.heightPixels;
            ps.width = dm.widthPixels;
            mFirstVIewHolder.mVideoView.setLayoutParams(ps);
            mFirstVIewHolder.mVideoView.refreshParams(dm.widthPixels, dm.heightPixels);

            RelativeLayout.LayoutParams psBg = (RelativeLayout.LayoutParams) mBlurBk.getLayoutParams();
            psBg.height = FrameLayout.LayoutParams.MATCH_PARENT;
            psBg.width = FrameLayout.LayoutParams.MATCH_PARENT;
            mBlurBk.setLayoutParams(psBg);
        } else {
            int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
            RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) mFirstVIewHolder.mVideoView.getLayoutParams();
//            //按比例缩放直播窗体
            int liveViewHight = (int) (width * 0.75f);  // 4:3
            ps.height = liveViewHight;
            mFirstVIewHolder.mVideoView.setLayoutParams(ps);
            mFirstVIewHolder.mVideoView.setViewParams(mWidth, liveViewHight);
            mFirstVIewHolder.mVideoView.refreshParams(mWidth, liveViewHight);

            RelativeLayout.LayoutParams psBg = (RelativeLayout.LayoutParams) mBlurBk.getLayoutParams();
            psBg.height = liveViewHight;
            psBg.width = mWidth;
            mBlurBk.setLayoutParams(psBg);
        }
    }

    public void changeDanmu(View view) {
        mCountTime = 0;
        if (mFirstVIewHolder.mDanmakuView.isShown()) {
            mFirstVIewHolder.mDanmakuView.hide();
            view.setSelected(false);
            Toast.makeText(getActivity(), getString(R.string.live_danmu_hide), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), getString(R.string.live_danmu_show), Toast.LENGTH_SHORT).show();
            view.setSelected(true);
            mFirstVIewHolder.mDanmakuView.show();
        }
    }

    private void changeTitleTab() {
        if (mIsLandView) {
            mFirstVIewHolder.ibtn1.setSelected(true);
            mFirstVIewHolder.ibtn1.setImageResource(R.drawable.danmu_bg);
        } else {
            mFirstVIewHolder.ibtn1.setImageResource(R.drawable.vedio_full);
        }
    }

    /**
     * 设置艺人信息
     */
    private void updateViewInfo(final StarModel starModel) {
        if (getActivity().isFinishing() || starModel == null) {
            return;
        }
        if (mFirstVIewHolder != null) {
            mFirstVIewHolder.iBtnController.setOnClickListener(this);
            mFirstVIewHolder.iBtnNext.setOnClickListener(this);
            mFirstVIewHolder.mVideoView.setOnCompletionListener(this);
            mFirstVIewHolder.mVideoView.setOnPreparedListener(this);
            mFirstVIewHolder.mVideoView.setOnErrorListener(this);
            mFirstVIewHolder.ibtnBack.setOnClickListener(this);
            mFirstVIewHolder.ibtn1.setOnClickListener(this);
            mFirstVIewHolder.ibtn2.setOnClickListener(this);
            mFirstVIewHolder.btnGift.setOnClickListener(this);
            mFirstVIewHolder.tvName.setText(starModel.getNickName());
            Glide.with(this).load(starModel.getPhoto()).transform(new GlideRoundTransform(getContext(), R.dimen.height_35dp)).into(mFirstVIewHolder.ivIcon);
        }

        if (mSecondViewHolder != null) {
            mSecondViewHolder.ivTag.setBackgroundResource(RoleUtil.getRoleIcon(starModel.getRole()));
            mSecondViewHolder.tvName.setText(starModel.getNickName());
            mSecondViewHolder.tvDes.setText(starModel.getRanking());
            Glide.with(this).load(StringUtil.isNullorEmpty(starModel.getPhoto()) ? R.drawable.default_icon : starModel.getPhoto())
                    .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                    .transform(new GlideRoundTransform(getActivity(), R.dimen.height_76dp)).into(mSecondViewHolder.ivICon);
            Glide.with(this).load(StringUtil.isNullorEmpty(starModel.getPhoto()) ? R.drawable.default_icon : starModel.getPhoto())
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap overlay, GlideAnimation<? super Bitmap> arg1) {
                            long startMs = System.currentTimeMillis();
                            overlay = FastBlur.blur(overlay);
                            L.d(TAG + "ms", System.currentTimeMillis() - startMs + "ms");
                            mBlurBk.setImageBitmap(overlay);
                        }
                    });

            mSecondViewHolder.btnAttention.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    attentionClick(starModel, v);
                }
            });

            List<String> tags = starModel.getTags();
            for (int i = 0; i < tags.size() && i < 3; i++) {
                LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                View view = layoutInflater.inflate(
                        R.layout.layout_star_room_tag_btn, null);
                TextView tagBtn = (TextView) view.findViewById(R.id.tagBtn);
                tagBtn.setText(tags.get(i));
                mSecondViewHolder.tagViewGroup.addView(view);
                L.d(TAG, tags.get(i));
            }
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            View addTagView = layoutInflater.inflate(
                    R.layout.layout_star_room_add_tag_btn, null);
            addTagView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                    Intent intent = new Intent(getActivity(), StarTagActivity.class);
                    intent.putExtra(StarTagActivity.KEY_STAR, starModel);
                    startActivity(intent);
                }
            });
            mSecondViewHolder.tagViewGroup.addView(addTagView);
        }
        if (mThridViewHolder != null) {
            if (!StringUtil.isNullorEmpty(starModel.getXingzuo())) {
                mThridViewHolder.tvConstellation.setText(starModel.getXingzuo());
            } else {
                mThridViewHolder.tvConstellation.setText(getString(R.string.satr_info_normal));
            }
            if (!StringUtil.isNullorEmpty(starModel.getAge())) {
                mThridViewHolder.tvGender.setText(getString(R.string.satr_age, starModel.getAge()));
            } else {
                mThridViewHolder.tvGender.setText(getString(R.string.satr_info_normal));
            }
            if (!StringUtil.isNullorEmpty(starModel.getCity())) {
                mThridViewHolder.tvLocation.setText(starModel.getCity());
            } else {
                mThridViewHolder.tvLocation.setText(getString(R.string.satr_info_normal));
            }
            String intr = starModel.getIntr();
            mThridViewHolder.tvIntroduce.setText(StringUtil.isNullorEmpty(intr) ? "这个人很懒，啥也没写" : intr);
        }
        //改变粉她按钮
        changeFollowBtn(starModel);
    }

    private void attentionClick(StarModel starModel, View v) {
        if (isLogin()) {
            if (mIsFollow) {
                //取消粉
                cancleFollow(starModel.getUid());
            } else {
                //粉她
                followStar(starModel.getUid());
            }
        } else {
            jumpToLogin("登录以后才可以粉TA哦~");
        }
    }

    private void followStar(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("token", getToken())
                .add("followid", starId)
                .build();
        post(BuildConfig.URL_ADD_FOLLOW, body);
    }

    private void cancleFollow(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("token", getToken())
                .add("followid", starId)
                .build();
        post(BuildConfig.URL_REMOVE_FOLLOW, body);
    }


    private void initStarInfo() {
        //刷新列表
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", mStarModel.getUid())
                .build();
        post(BuildConfig.URL_STAR_INFO, body);
    }


    private void setDanmuView() {
        // 设置最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 6); // 滚动弹幕最大显示6行
        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);

        DanmakuContext mContext = DanmakuContext.create();
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3).setDuplicateMergingEnabled(false).setScrollSpeedFactor(1.2f).setScaleTextSize(1.2f)
//        .setCacheStuffer(new BackgroundCacheStuffer())  // 绘制背景使用BackgroundCacheStuffer
                .setMaximumLines(maxLinesPair)
                .preventOverlapping(overlappingEnablePair);

        BaseDanmakuParser mParser = createParser(this.getResources().openRawResource(R.raw.comments));
        mDanMuUtil = new DanMuUtil(mContext, mFirstVIewHolder.mDanmakuView, mParser);
        mFirstVIewHolder.mDanmakuView.setCallback(new DrawHandler.Callback() {
            @Override
            public void updateTimer(DanmakuTimer timer) {
            }

            @Override
            public void drawingFinished() {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {
            }

            @Override
            public void prepared() {
                mFirstVIewHolder.mDanmakuView.start();
            }
        });
        mFirstVIewHolder.mDanmakuView.prepare(mParser, mContext);
        mFirstVIewHolder.mDanmakuView.enableDanmakuDrawingCache(true);
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_STAR_DYNAMIC.equals(url)) {
            if (StringUtil.isNullorEmpty(mCurrId)) {
                return JSON.parseArray(resultModel.getData(), StarVideoModel.class);
            } else {
                List<StarVideoModel> videoList = JSON.parseArray(resultModel.getData(), StarVideoModel.class);
                if (videoList != null) {
                    for (int i = 0; i < videoList.size(); i++) {
                        StarVideoModel starVidemodel = videoList.get(i);
                        VideoModel videoModel = starVidemodel.getVideo();
                        if (mCurrId.equals(starVidemodel.getDynamicId()) || (videoModel != null && mCurrId.equals(videoModel.getUrl()))) {
                            videoList.remove(i);
                            mVideoList.add(0, starVidemodel);
                            break;
                        }
                    }
                }
                return videoList;
            }
        } else if (url.contains(BuildConfig.URL_GET_VIDEO_URL)) {
            return JSON.parseObject(resultModel.getData(),VODModel.class);
        }
        return super.asyncExecute(url, resultModel);
    }

    private BaseDanmakuParser createParser(InputStream stream) {
        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }
        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);
        BaseDanmakuParser parser = new BiliDanmukuParser();
        if (loader != null) {
            try {

                loader.load(stream);
            } catch (IllegalDataException e) {
                e.printStackTrace();
            }
            IDataSource<?> dataSource = loader.getDataSource();
            parser.load(dataSource);
        }
        return parser;
    }


    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        if (BuildConfig.URL_ADD_FOLLOW.equals(url)) {
            initStarInfo();
            if (mSecondViewHolder != null && mSecondViewHolder.btnAttention != null && mPersonValueAnim != null) {
                mPersonValueAnim.startPersonValueAnim(mSecondViewHolder.btnAttention);
            }

            Toast.makeText(getActivity(), "已粉TA", Toast.LENGTH_SHORT).show();
            L.d(TAG, "关注成功");

        } else if (BuildConfig.URL_REMOVE_FOLLOW.equals(url)) {
            initStarInfo();
            Toast.makeText(getActivity(), "已取消粉TA", Toast.LENGTH_SHORT).show();
            L.d(TAG, "删除关注成功");
        } else if (BuildConfig.URL_STAR_INFO.equals(url)) {
            StarModel starModel = JSON.parseObject(resultModel.getData(), StarModel.class);

            changeFollowBtn(starModel);
            if (mCallback != null) {
                mCallback.followStarChange(starModel);
            }
        } else if (BuildConfig.URL_STAR_DYNAMIC.equals(url)) {
            List<StarVideoModel> videoList = (List<StarVideoModel>) resultModel.getDataModel();
            mVideoList.addAll(videoList);
            if (mCurPosition == -1 && mVideoList.size() > 0) {
                if (hasDisplayHintView()) {
                    mFirstVIewHolder.ivHint.setVisibility(View.VISIBLE);
                }
                if (mVideoList.size() > 0) {
                    mLiveMsgView = new LiveMsgView(getActivity(), mWidth, mFirstVIewHolder.mFlMsg);
                    startVideoByVideo(0);
                    displayVideoController();
                    if (mAutoRotateOn) {
                        Activity activity = getActivity();
                        if (activity != null) {
                            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                        }
                    }
                } else {
                    mLoadingView.dismiss();
                }
            } else {
                mViewFlipper.removeViewAt(0);
                mLoadingView.dismiss();
                mViewTitle.setVisibility(View.VISIBLE);
            }
            dispalyFlipperView();
            if (videoList.size() < VIDEO_PAGE_SIZE) {
                mLoadOver = true;
            }
            int size = mViewFlipper.getChildCount();
            initDots(size);

        } else if (BuildConfig.URL_GET_VIDEO_URL.equals(url)) {
            VODModel vod = (VODModel) resultModel.getDataModel();
            if(vod != null){
                if(vod.isMgtvType()){
                    getVodUrl(vod.getPlayUrl());
                }else {
                    playVod(vod.getPlayUrl());
                }
            }
        }else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url)) {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", "", true);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(BuildConfig.URL_GET_IS_FOLLOWED.equals(url)) {
            try {
                if (mSecondViewHolder == null) {
                    return;
                }
                JSONObject jsonData = new JSONObject(resultModel.getData());
                boolean isFollow = jsonData.getBoolean("isFollowed");
                mIsFollow = isFollow;
                if (isFollow) {
                    int bottom = mSecondViewHolder.btnAttention.getPaddingBottom();
                    int top = mSecondViewHolder.btnAttention.getPaddingTop();
                    int right = mSecondViewHolder.btnAttention.getPaddingRight();
                    int left = mSecondViewHolder.btnAttention.getPaddingLeft();
                    mSecondViewHolder.btnAttention.setBackgroundResource(R.drawable.star_detail_attention_yes_bg);
                    mSecondViewHolder.btnAttention.setPadding(left, top, right, bottom);
                    mSecondViewHolder.ivAttention.setImageDrawable(getResources().getDrawable(R.drawable.star_attention_yes_icon));
                    if(mStarModel != null)
                    {
                        mSecondViewHolder.tvAttention.setText(mStarModel.getFans());
                    }
                } else {
                    int bottom = mSecondViewHolder.btnAttention.getPaddingBottom();
                    int top = mSecondViewHolder.btnAttention.getPaddingTop();
                    int right = mSecondViewHolder.btnAttention.getPaddingRight();
                    int left = mSecondViewHolder.btnAttention.getPaddingLeft();
                    mSecondViewHolder.btnAttention.setBackgroundResource(R.drawable.star_detail_attention_bg);
                    mSecondViewHolder.btnAttention.setPadding(left, top, right, bottom);
                    mSecondViewHolder.ivAttention.setImageDrawable(getResources().getDrawable(R.drawable.star_attention_icon));
                    mSecondViewHolder.tvAttention.setText(getString(R.string.attention));
                }
            }catch (Exception e){

            }
        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if (BuildConfig.URL_GET_VIDEO_URL.equals(url)) {
            // TODO: 2016/6/20 先注释,这里不需要调用startVideo吧?
//            startVideo(resultModel.getDataModel().toString());

        } else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                //把code转成2开头
                String responseCode = resultModel.getResponseCode();
                if(!StringUtil.isNullorEmpty(responseCode)){
                    String subFirst = responseCode.substring(0,1);
                    responseCode = responseCode.replace(subFirst,"2");
                }
                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", responseCode, false);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        mLoadingView.dismiss();
    }

    //点播类型为MGTV时缓存请求URl
    private String mVodRequestUrl;

    private void getVodUrl(String url){
        mVodRequestUrl = url;
        if(!StringUtil.isNullorEmpty(mVodRequestUrl)){
            get(url,null);
        }
    }

    private void playVod(String url){
        startVideo(url);
    }

    private void dispalyFlipperView() {
        AlphaAnimation animation = new AlphaAnimation(0, 1.0f);
        animation.setDuration(500);
        animation.setFillAfter(true);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mViewFlipper.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mViewFlipper.startAnimation(animation);
    }

    private void startVideoByVideo(int position) {
        int i = position;
        if (i >= mVideoList.size()) {
            i = 0;
        }

        for (; i < mVideoList.size(); i++) {
            StarVideoModel startModel = mVideoList.get(i);
            if (startModel != null) {
                VideoModel videoModel = startModel.getVideo();
                if (videoModel != null) {
                    mCurPosition = i;
                    getVideoUrl(videoModel.getUrl());
                    if (mFirstVIewHolder != null) {
                        mFirstVIewHolder.tvTitle.setText(startModel.getContent());
                    }
                    if (!mLoadOver && i == mVideoList.size() - 1) {
                        mPage++;
                        getVideoList();
                    }
                    break;
                }
            }
        }
    }

    private void getVideoUrl(String video) {
        mCurrVideo = video;
        Map<String, String> requestBody = new FormEncodingBuilderEx()
                .add(Constant.KEY_MEDIAID, video)
                .add(Constant.KEY_RATE, "SD")
                .add(Constant.KEY_TYPE, "key")
                .add(Constant.KEY_USER_ID, getUid()).build();
        L.d(TAG, video);
        post(BuildConfig.URL_GET_VIDEO_URL, requestBody);
    }

    private void startVideo(String videoPath) {
        mCurrVideoPath = videoPath;
        if (!NetworkUtils.isWifi() && !mHasNotify) {
            NotifyDialog dialog = new NotifyDialog(getActivity());
            dialog.setOnButtonClickListener(this);
            dialog.show(videoPath);
        } else {
            setVideoPath();
            mFirstVIewHolder.mVideoView.requestFocus();
            mFirstVIewHolder.mVideoView.start();

            Log.i("PlayStadus", "start");
            //开启上报卡顿信息
            String host = StringUtil.getUrlHost(videoPath);
            String path = "";
            if(!StringUtil.isNullorEmpty(host)){
                path = videoPath.substring(host.length()+7);
            }
            try {
                path = URLEncoder.encode(path, "UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, "0");
        }
    }

    private void setVideoPath() {
        Map<String, String> params = new HashMap<>();
        params.put("auid", mStarModel.getUid());
        params.put("mid", mCurrVideo);
        params.put("ap", "1");
        mFirstVIewHolder.mVideoView.setVideoPath(mCurrVideoPath, params, IjkVideoView.VideoType.vod);
    }


    private void showLoadingView() {
        Activity activity = getActivity();
        if (activity != null && !activity.isFinishing()) {
            mLoadingView.showAtLocation();
        }
    }

    private void displayVideoController() {
        synchronized (mIsAnim) {
            if (!mIsAnim) {
                mIsAnim = true;
                if (mFirstVIewHolder.llTitle.getVisibility() != View.VISIBLE) {
                    mCountTime = 0;
                    mHandler.sendEmptyMessageDelayed(MSG_TYPE_CHECK_DISPLAY, 1000);
                    if (mVideoList.size() > 1) {
                        mFirstVIewHolder.iBtnNext.setVisibility(View.VISIBLE);
                    }
                    mFirstVIewHolder.iBtnController.setVisibility(View.VISIBLE);
                    mFirstVIewHolder.llTitle.clearAnimation();
                    mFirstVIewHolder.llTitle.startAnimation(mAnimationUpToDown);
                    if (mIsLandView) {
                        mFirstVIewHolder.llStarInfo.startAnimation(mAnimationDownToUp);
                    }
                } else {
                    mFirstVIewHolder.iBtnNext.setVisibility(View.GONE);
                    mFirstVIewHolder.iBtnController.setVisibility(View.GONE);
                    mFirstVIewHolder.llTitle.clearAnimation();
                    mFirstVIewHolder.llTitle.startAnimation(mAnimationUpToDownBack);
                    if (mIsLandView && mFirstVIewHolder.llStarInfo.getVisibility() == View.VISIBLE) {
                        mFirstVIewHolder.llStarInfo.startAnimation(mAnimationDownToUpBack);
                    }
                }
            }
        }
    }

    private void showVideoErrorView() {
        Activity activity = getActivity();
        if (activity != null && !activity.isFinishing()) {
            if (mLoadingView != null) {
                mLoadingView.dismiss();
            }
            if (mLoadingViewHelper != null) {
                mLoadingViewHelper.show(getContext().getString(R.string.load_error), R.drawable.video_load_error, getContext().getString(R.string.refresh), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLoadingViewHelper.restore();
                        showLoadingView();
                        startVideo(mCurrVideoPath);
                    }
                }, new LoadingViewHelper.CustomListener() {
                    @Override
                    public void custom(View view, TextView text, Button btn) {
                        view.setBackgroundColor(getResources().getColor(R.color.live_alpha_black));
                        text.setTextColor(getResources().getColor(R.color.white));
                    }
                });
            }
        }
    }

    private void changeFollowBtn(StarModel starModel) {
        if(starModel == null ){
            return;
        }
        if(isLogin()){
            Map<String, String> param = new FormEncodingBuilderEx()
                    .add("uid", MaxApplication.getInstance().getUid())
                    .add("token", MaxApplication.getInstance().getToken())
                    .add("artistId", starModel != null ? starModel.getUid() : "").build();
            post(BuildConfig.URL_GET_IS_FOLLOWED, param);
        }
    }

    private void getVideoList() {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("artistId", mStarModel.getUid())
                .add("uId",getUid())
                .add("token",getToken())
                .add("page", "" + mPage).add("pageSize", "" + VIDEO_PAGE_SIZE)
                .add("dyType","1")
                .build();
        post(BuildConfig.URL_STAR_DYNAMIC, body);
    }

//    public boolean onTouch(MotionEvent ev) {
//        return mDetector.onTouchEvent(ev);
//    }


    @Override
    public boolean onDown(MotionEvent e) {
        this.mViewFlipper.setClickable(true);
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        if (mViewFlipper.getChildCount() == 3 && mViewFlipper.getCurrentView() == mViewFlipper.getChildAt(0)) {
            mFirstVIewHolder.ivHint.setVisibility(View.GONE);
            displayVideoController();
        }
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        this.mViewFlipper.setClickable(false);
        if (e1 == null || e2 == null || mIsLandView) {
            return false;
        }
        if (e1.getX() - e2.getX() > 120) {
            if (mViewFlipper.getCurrentView() != mViewFlipper.getChildAt(mViewFlipper.getChildCount() - 1)) {
                mFirstVIewHolder.ivHint.setVisibility(View.GONE);
                this.mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this.getActivity(),
                        R.anim.slide_left_in));
                this.mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this.getActivity(),
                        R.anim.slide_left_out));
                mViewFlipper.showNext();
                changeDot(DOT_RIGHT);
                if (mViewFlipper.getChildCount() == 3 && mViewFlipper.getCurrentView() != mViewFlipper.getChildAt(0)) {
                    mViewTitle.setVisibility(View.VISIBLE);
                    Activity activity = getActivity();
                    if (activity != null) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                } else if (mViewFlipper.getChildCount() == 3 && mViewFlipper.getCurrentView() == mViewFlipper.getChildAt(0)) {
                    if (mAutoRotateOn) {
                        Activity activity = getActivity();
                        if (activity != null) {
                            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                        }
                    }
                }
                int page = -1;
                for (int i = 0; i < mViewFlipper.getChildCount(); i++) {
                    if (mViewFlipper.getCurrentView() == mViewFlipper.getChildAt(i)) {
                        page = i + 1;
                        break;
                    }
                }
                if (mViewFlipper.getChildCount() != 3) {
                    page += 1;
                }
                if (page != -1) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("t", "p" + page);
                }
                return true;
            }
        } else if (e1.getX() - e2.getX() < -120) {
            if (mViewFlipper.getCurrentView() != mViewFlipper.getChildAt(0)) {
                this.mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this.getActivity(),
                        R.anim.slide_right_in));
                this.mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this.getActivity(),
                        R.anim.slide_right_out));
                changeDot(DOT_LEFT);
                mViewFlipper.showPrevious();
                Activity activity = getActivity();
                if (mViewFlipper.getChildCount() == 3 && mViewFlipper.getCurrentView() == mViewFlipper.getChildAt(0)) {
                    mViewTitle.setVisibility(View.GONE);
                    if (mAutoRotateOn && activity != null) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                    }
                } else if (mViewFlipper.getChildCount() == 3 && mViewFlipper.getCurrentView() != mViewFlipper.getChildAt(0)) {
                    if (activity != null) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                }
                int page = -1;
                for (int i = 0; i < mViewFlipper.getChildCount(); i++) {
                    if (mViewFlipper.getCurrentView() == mViewFlipper.getChildAt(i)) {
                        page = i + 1;
                        break;
                    }
                }
                if (mViewFlipper.getChildCount() != 3) {
                    page += 1;
                }
                if (page != -1) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("t", "p" + page);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseVideo();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mStarModel != null)
        {
            changeFollowBtn(mStarModel);
        }
        resumVideo();
        mFirstVIewHolder.iBtnController.setSelected(!mIsPlaying);
        if (!mShowLoading) {
            mShowLoading = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mFirstVIewHolder != null && mFirstVIewHolder.mVideoView != null && !mFirstVIewHolder.mVideoView.isPlaying() && NetworkUtils.hasNetwork() && mViewFlipper.getChildCount() == 3) {
                        showLoadingView();
                    }
                }
            }, 1000);
        }
        mAutoRotateOn = (android.provider.Settings.System.getInt(getActivity().getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
    }


    @Override
    public void onStop() {
        super.onStop();
        if (mFirstVIewHolder.mVideoView != null && mFirstVIewHolder.mVideoView.isPlaying()) {
            if (!mFirstVIewHolder.mVideoView.isBackgroundPlayEnabled()) {
                mFirstVIewHolder.mVideoView.release(true);
                mFirstVIewHolder.mVideoView.stopPlayback();
                mFirstVIewHolder.mVideoView.stopBackgroundPlay();
                IjkMediaPlayer.native_profileEnd();

                //停止视频卡顿信息上报
                PlayMessageUploadMannager.getInstance().stopUploadMessage();
                //完成上报
                PlayMessageUploadMannager.getInstance().doneUpMessage();

            } else {
                mFirstVIewHolder.mVideoView.enterBackground();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ibtn_star_info_video_controller) {
            mCountTime = 0;
            if (mFirstVIewHolder.mVideoView.isPlaying()) {
                v.setSelected(true);
                mFirstVIewHolder.mVideoView.pause();
            } else {
                v.setSelected(false);
                mFirstVIewHolder.mVideoView.start();
            }

        } else if (i == R.id.ibtn_star_info_video_next) {
            mCountTime = 0;

            //停止视频卡顿信息上报
            PlayMessageUploadMannager.getInstance().stopUploadMessage();
            //完成上报
            PlayMessageUploadMannager.getInstance().doneUpMessage();

            //播放下一个视频
            startVideoByVideo(mCurPosition + 1);


        } else if (i == R.id.ibtn_star_detail_video_title_2 || i == R.id.ll_star_detail_title_share) {
            shareVideo(mIsLandView);

        } else if (i == R.id.ibtn_star_detail_video_title_1) {
            if (mIsLandView) {
                if (mFirstVIewHolder.mDanmakuView != null) {
                    changeDanmu(v);
                }
            } else {
                Activity activity = getActivity();
                if (activity != null) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                if (mAutoRotateOn) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Activity activity = getActivity();
                            if (activity != null) {
                                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                            }
                        }
                    }, 3000);
                }
            }

        } else if (i == R.id.ibtn_star_detail_video_title_back || i == R.id.ll_star_detail_title_back) {
            int screenWidth, screenHeight;
            WindowManager windowManager = getActivity().getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            screenWidth = display.getWidth();
            screenHeight = display.getHeight();
            if (screenWidth < screenHeight) {
                //竖屏
                onBackPressed();
                getActivity().finish();
            } else {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                if (mAutoRotateOn) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Activity activity = getActivity();
                            if (activity != null) {
                                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                            }
                        }
                    }, 3000);
                }
            }

        } else if (i == R.id.ibtn_star_detail_gif) {
            if (!isLogin()) {
                jumpToLogin("登录以后才可以赠送礼物哦~");
                return;
            }
            if (mCallback != null) {
                mCallback.showGift();
            }

        }
    }

    private void shareVideo(boolean isFull) {
        mCountTime = 0;
        HashMap<String, String> map = new HashMap<>();
        map.put("c", "");
        if (mStarModel != null) {
            if (isFull) {
                mShareUtil.shareAsFull(getUid(), getToken(), ShareUtil.TYPE_ACTOR, "",mStarModel.getUid(), "","");
            } else {
                mShareUtil.share(getUid(), getToken(), ShareUtil.TYPE_ACTOR, "",mStarModel.getUid(), "","");
            }
        }
    }

    public boolean hasDisplayHintView() {
        boolean display;
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(getActivity().getPackageName() + "star_video", Context.MODE_PRIVATE);
        display = sharedPreferences.getBoolean("star_video", true);
        if (display) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("star_video", false);
            editor.apply();
        }
        return display;
    }

    public boolean onBackPressed() {
        if (mIsLandView) {
            Activity activity = getActivity();
            if (activity != null) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            if (mAutoRotateOn) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Activity activity = getActivity();
                        if (activity != null) {
                            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                        }
                    }
                }, 3000);
            }
            return true;
        } else {
            if (mFirstVIewHolder.mVideoView != null) {
                if (!mFirstVIewHolder.mVideoView.isBackgroundPlayEnabled()) {
                    mFirstVIewHolder.mVideoView.stopPlayback();
                    mFirstVIewHolder.mVideoView.release(true);
                    mFirstVIewHolder.mVideoView.stopBackgroundPlay();

                    //停止视频卡顿信息上报
                    PlayMessageUploadMannager.getInstance().stopUploadMessage();
                    //完成上报
                    PlayMessageUploadMannager.getInstance().doneUpMessage();
                } else {
                    mFirstVIewHolder.mVideoView.enterBackground();
                }
            }
            IjkMediaPlayer.native_profileEnd();
            return false;
        }

    }

    @Override
    public void onCompletion(IMediaPlayer mp) {

        //停止视频卡顿信息上报
        PlayMessageUploadMannager.getInstance().stopUploadMessage();
        //完成上报
        PlayMessageUploadMannager.getInstance().doneUpMessage();

        startVideoByVideo(mCurPosition + 1);
        mFirstVIewHolder.iBtnController.setSelected(!mp.isPlaying());
        mFirstVIewHolder.tvNextInfo.setVisibility(View.GONE);

    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {

        //出错上报
        PlayMessageUploadMannager.getInstance().errUpMessage(what,extra);

        Log.i("LiveVideo","OnErr--->"+what);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mLoadingView.dismiss();
            }
        }, 1100);

        showVideoErrorView();
        return false;
    }


    @Override
    public void onPrepared(IMediaPlayer mp) {

        mFirstVIewHolder.iBtnController.setSelected(false);
        mLoadingView.dismiss();
        mController.show();
    }

    @Override
    public synchronized boolean onInfo(IMediaPlayer mp, int what, int extra) {
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                Log.i("LiveVideo", "OnPuse");
                PlayMessageUploadMannager.getInstance().addPuseCount();
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                PlayMessageUploadMannager.getInstance().doErrCount();
                break;
        }
        return false;
    }

    public void setStarInfo(StarModel starModel, String dynamicId) {
        this.mCurrId = dynamicId;
        this.mStarModel = starModel;
        updateViewInfo(starModel);
        getVideoList();
    }

    public void screenOrietantionChanged(boolean island) {
        mIsLandView = island;
        if (island) {
            if (mFirstVIewHolder != null) {
                mFirstVIewHolder.progressBar.setVisibility(View.GONE);
                mFirstVIewHolder.mDanmakuView.show();
                mFirstVIewHolder.btnGift.setVisibility(View.VISIBLE);
            }
            if (dotLayout != null) {
                dotLayout.setVisibility(View.INVISIBLE);
            }
        } else {
            if (mFirstVIewHolder.progressBar != null) {
                mFirstVIewHolder.progressBar.setVisibility(View.VISIBLE);
                if (mFirstVIewHolder.mDanmakuView.isShown()) {
                    mFirstVIewHolder.mDanmakuView.hide();
                }
                mFirstVIewHolder.btnGift.setVisibility(View.GONE);
                mFirstVIewHolder.llStarInfo.setVisibility(View.GONE);
            }
            if (dotLayout != null) {
                dotLayout.setVisibility(View.VISIBLE);
            }
            mDanMuUtil.clearDanmu();
        }
        changeLayouParams();
        changeTitleTab();
        if (mLiveMsgView != null) {
            mLiveMsgView.changeScreenConfig();
        }
    }

    public void setOnStarDetailVideoCallBack(onStarDetailVideoCallBack callback) {
        this.mCallback = callback;
    }

    @Override
    public void onSure(String videoPath) {
        mHasNotify = true;
        startVideo(videoPath);
        mLoadingView.dismiss();
    }

    @Override
    public void onCancel() {
        mHasNotify = true;
        mLoadingView.dismiss();
    }

    @Override
    public void onCountdown(long time) {
        if (mIsLandView) {
            return;
        }
        if (time < 5 && time > 0) {
            mFirstVIewHolder.tvNextInfo.setVisibility(View.VISIBLE);
        } else {
            mFirstVIewHolder.tvNextInfo.setVisibility(View.GONE);
        }
    }


    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        if (animation == mAnimationUpToDownBack) {
            synchronized (mIsAnim) {
                mIsAnim = false;
            }
            mFirstVIewHolder.llTitle.setVisibility(View.GONE);
        } else if (animation == mAnimationUpToDown) {
            synchronized (mIsAnim) {
                mIsAnim = false;
            }
            mFirstVIewHolder.llTitle.setVisibility(View.VISIBLE);
        } else if (animation == mAnimationDownToUp) {
            mFirstVIewHolder.llStarInfo.setVisibility(View.VISIBLE);
        } else {
            mFirstVIewHolder.llStarInfo.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onDestroy() {
        if(mFirstVIewHolder != null)
        {
            if(mFirstVIewHolder.mDanmakuView!= null)
            {
//                mFirstVIewHolder.mDanmakuView.setCallback(null);
                mFirstVIewHolder.mDanmakuView.release();
                mFirstVIewHolder.mDanmakuView = null;
            }
           if(mFirstVIewHolder.mVideoView != null)
           {
               mFirstVIewHolder.mVideoView.setController(null);
           }
        }

        if(mController != null)
        {
            mController.onDestory();
        }
        mCallback = null;
        super.onDestroy();
    }

    class FirstViewHolder {
        View mRootView;
        IjkVideoView mVideoView;
        DanmakuView mDanmakuView;
        ImageButton iBtnController;
        ImageButton iBtnNext;
        TextView tvNextInfo;
        ProgressBar progressBar;
        ImageView ivHint;
        LinearLayout llTitle;
        LinearLayout ibtnBack;
        ImageButton ibtn1;
        ImageButton ibtn2;
        TextView tvTitle;
        FrameLayout mFlMsg;
        ImageButton btnGift;
        LinearLayout llStarInfo;
        ImageView ivIcon;
        TextView tvName;
        View mVideoErrorView;
    }

    class SecondViewHolder {
        ImageView ivICon;
        ImageView ivTag;
        TextView tvName;
        TextView tvDes;
        LinearLayout btnAttention;
        ImageView ivAttention;
        TextView tvAttention;
        LinearLayout tagViewGroup;
    }

    class ThridViewHolder {
        TextView tvConstellation;
        TextView tvGender;
        TextView tvLocation;
        TextView tvIntroduce;
    }


}
